package com.endgamefraction.androidinfection;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.content.Context;

import objectManager.CBaseObject;
import objectManager.CObjectManager;

public class GLRenderer implements android.opengl.GLSurfaceView.Renderer
{
	private GameThread mThread = null;
	private boolean loadTextures = true;
	public Context context = null;
	
	public void onSurfaceChanged(GL10 gl, int width, int height) 
	{
		// TODO Auto-generated method stub
		gl.glViewport(0, 0, width, height);
		
		/****
		 * set up openGL for 2D rendering
		 */
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glLoadIdentity();
		gl.glOrthof(0, width, height, 0, 0, 1);
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glDisable(GL10.GL_DEPTH_TEST);		
		
		gl.glEnable(GL10.GL_TEXTURE_2D);
	    gl.glEnable(GL10.GL_BLEND);
	    gl.glBlendFunc(GL10.GL_ONE, GL10.GL_SRC_COLOR);
	    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
	}

	public void onSurfaceCreated(GL10 gl, EGLConfig config) 
	{
		// TODO Auto-generated method stub
		//create and start the game thread 
		mThread = new GameThread();
		mThread.start();
		mThread.running = true;
	}
	
	public void onDrawFrame(GL10 gl) 
	{
		// clear screen
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		gl.glClearColor(0, 0, 0, 255);
		
		
		gl.glPushMatrix();
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glLoadIdentity();
		
		// go through and render the objectManager
		for(CBaseObject obj : CObjectManager.getObjectManager().getList())
		{
			gl.glPushMatrix();
			
			// translate the object
			gl.glTranslatef(obj.getPosX(), obj.getPosY(), 0.0f);
			
			if( loadTextures )
			{
				obj.setTexID(AssetManager.GetInstance().loadGameTexture(R.drawable.zombie1, context, gl));
			}
			
			// set the textures
			gl.glEnable(GL10.GL_TEXTURE_2D);
			gl.glBindTexture(GL10.GL_TEXTURE_2D, obj.getTextureID());
			// Enable the texture state
			gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
			// Point to our buffers
			gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, obj.getTexBuffer());
				

			// draw
			gl.glVertexPointer(3, GL10.GL_FLOAT, 0, obj.getVB());
			gl.glDrawElements(GL10.GL_TRIANGLES, obj.getNumIndices(), GL10.GL_UNSIGNED_SHORT, obj.getIB());
			
			// pop
			gl.glPopMatrix();
		}
		
		
		gl.glPopMatrix();
		
	}
	
	
}



